var baseurl = "http://markie.me/";
var bookmark_stat = "public";

function process_manage_db_return(data) {
    console.log("processing ajax return: " + data.info);
    if (data.info == 'need login') {
        $("#login").modal({opacity: 80});
    }
}

function fill_entry(entry, content) {
    $(entry).find('p.title').html(content.title);
    $(entry).find('p.description').html(content.text);
}

function reload(entry) {
    var loading = $(entry).find('img.temp-loading');
    var bid = $(entry).find('input[name="bookmark-id"]').val();

    $(loading).show();
    jQuery.ajax(baseurl + "manage_db.php?type=get-bookmark", {
        type: 'POST',
        data: {
            'id': bid,
        },
        success: function(data) {
            console.log(data);
             $(loading).hide();
            var content = data.entry;
            $(entry).find("button").remove();
            $(entry).slideUp('slow', function() {
                var old = $(entry).find('input[name="old"]').val();
                $(entry).find('textarea').replaceWith(old);
                fill_entry(entry, content);
                $(entry).slideDown();
                $("p.description").click(description_clicked);
            });
        },
        error: function(jqXHR, textStatus, erroThrown) {
            alert("error: " + textStatus);
            $(loading).hide();
        }
    });

    var id = $(entry).find('input[name="bookmark-id"]').val();
    console.log('reloading id: ' + id);
}

function add_new_clicked() {
    if ($.cookie("session") == null) {
        console.log("need login because session is null");
        $("#login").modal({opacity: 80});
        return;
    }

    var url = $("#newurl").val().trim();
    if (url == '') {
        url = new Date().getTime();
        url = url + "#" + Math.floor(Math.random() * 100000);
        $("#newurl").val(url);
        $("#extra").slideDown('slow');
        return;
    }

    if (url.indexOf('.') == -1) // this is a topic, not URL
        return;

    if (url.substring(0, 4) != "http") {
        url = "http://" + url;
        $("#newurl").val(url);
    }

    $("#loading").show();
    jQuery.ajax(baseurl + "cgi/get_title.py?url=" + url, {
        success: function(data) {
            $("#loading").hide();
            $("#extra").slideDown('slow', function() {
                resp = data;
                console.log(data);
                $("#new-title").val(resp.title);
                $("#new-desc").html(data.desc);
            });
        }
    });
}

function cancel_add_db_clicked() {
    $("#extra").slideUp('slow', function() {
        $("#new-title").val('');
        $('#new-desc').html('');
        $("#newurl").val('');
    });
}

function add_todb_clicked() {
    $("#loading").show();
    var url = $("#newurl").val().trim();
    jQuery.ajax(baseurl + "manage_db.php?type=add-bookmark", {
        type: "POST",
        data: {
            'url': url,
            'desc': $("#new-desc").val().trim(),
            'title': $("#new-title").val().trim(),
        },
        success: function(data) {
            process_manage_db_return(data);
            if (data.info == 'ok') {
                $(document).location = baseurl;
                location.reload();
            }
        },
        error: function(jqXHR, textStatus, erroThrown) {
            alert("error: " + textStatus);
        }
    });
}

function bookmark_mousein(event) {
    var target = event.target;
    $("img.remove-icon").hide();
    if ($(target).attr('class') != 'bookmark-entry') {
        target = $(target).parents('.bookmark-entry');
    }
    $(target).find('img.remove-icon').fadeIn();
}

function bookmark_mouseout(event) {
    var target = event.target;
    if ($(target).attr('class') != 'bookmark-entry') {
        target = $(target).parents('.bookmark-entry');
    }
    $(target).find('img.remove-icon').hide();
}

function remove_icon_clicked(event) {
    var target = event.target;
    var entry = $(target).parent('div.bookmark-entry');
    var url = $(entry).find('a.url-anchor');

    $('#loading').show();
    jQuery.ajax(baseurl + "manage_db.php?type=remove-bookmark", {
        type: 'POST',
        data: {
            'url': url.html(),
        },
        success: function(data) {
            $('#loading').hide();
            process_manage_db_return(data);
            if (data.info == "ok") {
                $(entry).slideUp('slow');
            }
        },
        error: function(jqXHR, textStatus, erroThrown) {
            alert("error: " + textStatus);
            $('#loading').hide();
        }
    });
}

function description_clicked(event) {
    var target = event.target;
    var entry = $(target).parents('div.bookmark-entry');
    var value = $(target).html();
    
    var edit = sprintf("<div class='temp-edit'>\
<textarea class='temp-edit' rows='10' cols='69' name='change-desc'>%s</textarea>\
<button class='submit-temp-edit'>Update</button>\
<button class='cancel-temp-edit'>Cancle</button>\
<input type='hidden' value='%s' name='old'/>\
<img src='img/loading.gif' width='15' height='15' class='temp-loading' /> \
</div>", value, $(target).prop('outerHTML'));
    $(target).fadeOut('fast', function() {
        $(target).replaceWith(edit);
        $(entry).find('div.temp-edit').fadeIn('slow');
        // Bind event handlers
        $("button.cancel-temp-edit").click(temp_edit_canceled);
        $("button.submit-temp-edit").click(temp_edit_submit);
    });
}

function temp_edit_submit(event) {
    var target = event.target;
    var entry = $(target).parents('div.bookmark-entry');
    var loading = $(entry).find('img.temp-loading');
    
    var bid = $(entry).find('input[name="bookmark-id"]').val();
    var desc = $(entry).find('textarea').val().trim();

    $(loading).show();
    jQuery.ajax(baseurl + "manage_db.php?type=edit-bookmark-desc", {
        type: 'POST',
        data: {
            'id': bid,
            'desc': desc,
        },
        success: function(data) {
            process_manage_db_return(data);
            reload(entry);
            $(loading).hide();
        },
        error: function(jqXHR, textStatus, erroThrown) {
            alert("error: " + textStatus);
            $(loading).hide();
        }
    });
}

function temp_edit_canceled(event) {
    var target = event.target;
    var entry = $(target).parents('div.bookmark-entry');
    var value = $(entry).find('input[name="old"]').val();

    console.log(value);
    $(entry).find('div.temp-edit').fadeOut('slow', function() {
        $(this).replaceWith(value);
        $("p.description").click(description_clicked);
    });
}

function newurl_keypressed(event) {
    
    if (event.which == 13) {
        add_new_clicked();
    }
}

function rate(event, value) {
    if ($.cookie("session") == null) {
        $("#login").modal({opacity: 80});
        return;
    }

    var target = event.target;
    var entry = $(target).parents('div.bookmark-entry');
    var bid = $(entry).find('input[name="bookmark-id"]').val();
    var rate = $(entry).find('span.rate');


    jQuery.ajax(baseurl + "manage_db.php?type=edit-bookmark-rate", {
        type: 'POST',
        data: {
            'id': bid,
            'rate': value,
        },
        success: function(data) {
            console.log("rate response: " + data.info);
            process_manage_db_return(data);
            if (data.info == "ok") {
                $(rate).slideUp('slow', function() {
                    $(rate).html(parseInt($(rate).html()) + value);
                    $(rate).slideDown();
                });
            }
        },
        error: function(jqXHR, textStatus, erroThrown) {
            alert("error: " + textStatus);
        }
    });
}

function rate_up(event) {
    rate(event, 1);
}

function rate_down(event) {
    rate(event, -1);
}

function kwick_clicked(event) {
    var li = $(event.target).parents('li');
    var li_id = $(li).attr("id");
    li_id = li_id.toString();
    if (li_id == "kwick-public") {
        if (bookmark_stat != 'public') {
            console.log("loading private bookmark");
            $("#loading").show();
            $("#bookmarks").load(baseurl + "index.php?get_public_bookmark", function() {
                $("#loading").hide();
                bookmark_stat = 'public';
            });
        }
    } else if (li_id == "kwick-private") {
        if (bookmark_stat != 'private') {
            console.log("loading private bookmark");
            $("#loading").show();
            $("#bookmarks").load(baseurl + "index.php?get_private_bookmark", function() {
                $("#loading").hide();
                bookmark_stat = 'private';
            });
        }
    } else if (li_id == "kwick-about") {
        if (bookmark_stat != 'about') {
            console.log("loading about page");
            $("#loading").show();
            $("#bookmarks").load(baseurl + "about.html", function() {
                $("#loading").hide();
                bookmark_stat = 'about';
            });
        }
    }
}

function login_btn_clicked(event) {
    $("#login-info").html("");
    var username = $("#username").val().trim();
    var password = $("#password").val().trim();
    var rem = 0;
    if ($('#remember_me').attr('checked'))
        rem = 1;
    $("#login-loading").show();
    jQuery.ajax(baseurl + "login.php", {
        type: "POST",
        data: {
            username: username,
            password: password,
            rem: rem
        },
        success: function(data) {
            console.log("login response: " + data.info);
            if (data.info == "fail") {
                $("#login-info").html("logging in failed");
            } else {
                $("#login-info").html("");
                var session = data.session;
                console.log("session: " + session);
                // set cookie
                if (rem == 1) {
                    console.log("remember me checked");
                    $.cookie('session', session, { expires: 30, path: '/' });
                } else {
                    console.log("remember me not checked");
                    $.cookie('session', session, {path: '/'});
                }
                $.modal.close();
            }
            $("#login-loading").hide();
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert("error: " + textStatus);
            $("#login-loading").hide();
        }
    });
}

$(document).ready(function() {
    $("#add-new-btn").click(add_new_clicked);
    $("#add-to-db").click(add_todb_clicked);
    $("#cancel-add-db").click(cancel_add_db_clicked);
    $(".bookmark-entry").hover(bookmark_mousein, bookmark_mouseout);
    $("img.remove-icon").click(remove_icon_clicked);
    $("p.description").click(description_clicked);
    $("#newurl").keypress(newurl_keypressed);
    $("img[src='img/up.png']").click(rate_up);
    $("img[src='img/down.png']").click(rate_down);
    $("#login-btn").click(login_btn_clicked);
    $("ul.kwicks li img").click(kwick_clicked);
    bookmark_stat = "public";
});

$().ready(function() {  
    $('.kwicks').kwicks({  
        max: 400,  
        spacing: 3,
        duration: 1500,  
        easing: 'easeOutBounce',
        sticky: true,
        event: "click",
    });  
});  